<template>
	<BasicModal
		@register="registerModalInner"
		:title="getTitle"
		width="900px"
		@ok="handleSubmit"
		@cancel="handleCancel"
		:showOkBtn="isStep1"
	>
		<a-steps :current="currentStep">
			<a-step v-for="item in steps" :key="item.title" :title="item.title" />
		</a-steps>
		<div class="pt-12 flex justify-center">
			<BasicForm @register="registerForm"> </BasicForm>
		</div>
		<template #insertFooter v-if="currentStep === 1">
			<a-button class="float-left" type="primary" @click="prev">上一步</a-button>
		</template>
		<template #centerFooter v-if="currentStep === 0">
			<a-button type="primary" @click="next">下一步</a-button>
		</template>
	</BasicModal>
</template>
<script lang="ts">
import { computed, defineComponent, ref, unref } from 'vue';
import { Steps, Step, Upload } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { BasicModal, BasicForm } from '#/components';
import { useForm, useModalInner } from '#/hooks';
import { DeptPersonTreeSelect } from '@/components/TreeSelect';
import {
	getBigTypes,
	getInspectUnitList,
	getSmallTypes,
	getPrincipaltree,
	addQuestion,
	getUserListByRoleId,
} from '@/api/demo';
import { useMessage } from '@/hooks/web/useMessage';

const steps = [
	{
		title: '选择类型',
	},
	{
		title: '创建问题',
	},
];

export default defineComponent({
	name: 'UseTableAddModal',
	components: {
		BasicModal,
		BasicForm,
		ASteps: Steps,
		AStep: Step,
		AUpload: Upload,
		PlusOutlined,
		DeptPersonTreeSelect,
	},
	emits: ['success', 'register'],
	setup(_, { emit }) {
		const isUpdate = ref(false);
		const currentStep = ref(0);
		let approveStatus = ref();

		let csrNames: string[];
		let unitePersonNames: string[];
		let supervisorId: number;

		// 第一步
		const isStep1 = computed(() => currentStep.value === 1);
		// 第二步 + 安健环隐患整改通知书
		const level20 = computed(() => approveStatus.value === 0 && currentStep.value === 1);
		// 第二步 + 安全生产检查情况记录表
		const level21 = computed(() => approveStatus.value === 1 && currentStep.value === 1);

		const { createMessage } = useMessage();

		const [registerForm, { validate, resetFields, getFieldValue }] = useForm({
			baseColProps: { span: 12 },
			baseRowStyle: {},
			schemas: [
				{
					field: 'approverStatus',
					label: '整改类型',
					component: 'RadioGroup',
					required: true,
					colProps: {
						span: 24,
					},
					show: () => !unref(isStep1),
					componentProps: {
						options: [
							{
								label: '安健环隐患整改通知书',
								value: 0,
							},
							{
								label: '安全生产检查情况记录表',
								value: 1,
							},
						],
					},
				},
				{
					field: 'number',
					label: '编号',
					component: 'Input',
					required: true,
					ifShow: () => level20.value,
				},
				{
					field: 'inspectUnit',
					label: '受检单位',
					component: 'ApiSelect',
					required: true,
					ifShow: () => isStep1.value,
					// more details please refer to the ApiSelect components
					componentProps: {
						api: getInspectUnitList,
						params: { type: 'SecurityInspectUnit' },
						labelField: 'name',
						valueField: 'name',
						immediate: false,
						mode: 'multiple',
					},
				},
				{
					field: 'typeBigId',
					label: '大类',
					component: 'ApiSelect',
					required: true,
					ifShow: () => isStep1.value,
					componentProps: ({ formModel, formActionType }) => {
						return {
							api: getBigTypes,
							resultField: 'data',
							labelField: 'name',
							valueField: 'id',
							onChange: async e => {
								const { updateSchema } = formActionType;
								if (!e) {
									delete formModel.typeSmallId;
									updateSchema({
										field: 'typeSmallId',
										componentProps: {
											options: [],
										},
									});
									return;
								}
								const typeSmall = await getSmallTypes(e);
								formModel.typeSmallId = null;

								updateSchema({
									field: 'typeSmallId',
									componentProps: {
										options: typeSmall,
									},
								});
							},
						};
					},
				},
				{
					field: 'inspectPart',
					label: '受检部位',
					component: 'Input',
					required: true,
					ifShow: () => level21.value,
				},
				{
					field: 'typeSmallId',
					label: '小类',
					component: 'ApiSelect',
					ifShow: () => isStep1.value,
					componentProps: {
						labelField: 'name',
						valueField: 'id',
						options: [],
					},
				},
				{
					field: 'inspectPurpose',
					label: '检查目的及内容',
					component: 'InputTextArea',
					required: true,
					ifShow: () => level21.value,
				},
				{
					field: 'unitePersonIds',
					component: 'DeptPersonTreeSelect',
					label: '联合发起人',
					ifShow: () => level21.value,
					componentProps: {
						api: getPrincipaltree,
						resultField: 'data',
						showSearch: true,
						allowClear: true,
						treeCheckable: true,
						onLabelChange: (e: any) => {
							unitePersonNames = e;
						},
					},
				},
				{
					field: 'inspectResult',
					label: '检查结果',
					component: 'InputTextArea',
					required: true,
					ifShow: () => level20.value,
				},
				{
					field: 'supervisorName',
					component: 'ApiSelect',
					label: '监理',
					required: true,
					ifShow: () => level21.value,
					componentProps: {
						api: getUserListByRoleId,
						params: 429100580470784,
						resultField: 'data',
						allowClear: true,
						valueField: 'name',
						labelField: 'name',
						onLabelChange: (e: Recordable[]) => {
							e && (supervisorId = e[0].userId);
						},
					},
				},
				{
					field: 'imgIds',
					label: '图片',
					required: true,
					ifShow: () => isStep1.value,
					component: 'PictureCardUpload',
					componentProps: {
						maxSize: 5,
						maxNumber: 3,
					},
				},
				{
					field: 'csrIds',
					component: 'DeptPersonTreeSelect',
					label: '抄送人',
					ifShow: () => isStep1.value,
					componentProps: {
						api: getPrincipaltree,
						resultField: 'data',
						showSearch: true,
						allowClear: true,
						treeCheckable: true,
						onLabelChange: (e: any) => {
							csrNames = e;
						},
					},
				},
				{
					field: 'inspectDate',
					label: '检查日期',
					component: 'DatePicker',
					required: true,
					ifShow: () => level20.value,
					componentProps: {
						valueFormat: 'YYYY-MM-DD',
					},
				},
				{
					field: 'accessoryUrl',
					label: () => (level20.value ? '通知书' : '附件'),
					component: 'SimpleUpload',
					required: true,
					ifShow: () => isStep1.value,
					componentProps: {
						maxSize: 5,
						maxNumber: 1,
					},
				},
				{
					field: 'reformDate',
					label: '整改期限',
					component: 'DatePicker',
					required: true,
					ifShow: () => isStep1.value,
					componentProps: {
						valueFormat: 'YYYY-MM-DD',
					},
				},
				{
					field: 'reformOpinion',
					label: '整改意见',
					component: 'InputTextArea',
					required: true,
					ifShow: () => level21.value,
				},
				{
					field: 'creatorDate',
					label: '创建时间',
					component: 'DatePicker',
					required: true,
					ifShow: unref(isUpdate),
					componentProps: {
						valueFormat: 'YYYY-MM-DD',
					},
				},
			],
			showActionButtonGroup: false,
		});

		const [registerModalInner, { setModalProps, closeModal }] = useModalInner(async data => {
			resetFields();
			console.log(data);
			isUpdate.value = !!data?.isUpdate;
		});

		const getTitle = computed(() => (!unref(isUpdate) ? '创建问题' : '编辑事件'));

		function next() {
			validate(['approverStatus']).then(
				() => {
					currentStep.value = 1;
				},
				err => {
					console.log(err);
				},
			);
			approveStatus.value = Number(getFieldValue('approverStatus'));
		}

		function prev() {
			currentStep.value = 0;
		}

		async function handleSubmit() {
			try {
				const values = await validate();
				setModalProps({ confirmLoading: true });
				values.approveBranch = 1;
				values.inspectUnit = values.inspectUnit?.join();
				values.csrNames = csrNames?.join();
				values.unitePersonNames = unitePersonNames?.join();
				values.csrIds = values.csrIds?.join();
				values.accessoryUrl = values.accessoryUrl?.[0];
				values.approverStatus == 1 && (values.supervisorId = supervisorId);
				console.log('submit values', values);
				await addQuestion(values);
				closeModal();
				createMessage.success('操作成功');
				emit('success');
			} catch (error) {
				console.error(error);
				createMessage.error('操作失败');
			} finally {
				setModalProps({ confirmLoading: false });
			}
		}

		function handleCancel() {
			resetFields();
			currentStep.value = 0;
		}

		return {
			registerModalInner,
			registerForm,
			getTitle,
			currentStep,
			steps,
			isUpdate,
			handleSubmit,
			handleCancel,
			isStep1,
			next,
			prev,
			getPrincipaltree,
		};
	},
});
</script>
